package com.cheetah.start.common.valid;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.cheetah.start.common.valid.anno.ValidDate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Date;

public class ValidDateValidator implements ConstraintValidator<ValidDate, String> {

    private String pattern = StrUtil.EMPTY;

    @Override
    public void initialize(ValidDate constraintAnnotation) {
        pattern = constraintAnnotation.pattern();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return true;
        }
        try {
            DateTime parse = DateUtil.parse(value, pattern);
            Date date = parse.toJdkDate();
            if (date == null) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
